import React, { useState, useEffect, Key } from 'react';
import { Drawer, Tag, Space } from 'antd';
import { connect, Dispatch } from 'umi';
import { LINE_INIT,
  LINE_LIST,
  LINE_ADD,
  LINE_UPDATE,
  LINE_DELETE,
  UPDATE_STATE } from '@/actions/line';
import ProCard from '@ant-design/pro-card';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import {PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import AGrid, { AGridButtonCallBackModel } from '@/components/SelfComp/AGrid';
import AButton from '@/components/SelfComp/AButton';
import { ConnectState } from '@/models/connect';
import { DataItem } from '@/models/common';
import { getItemValue } from '@/utils/commons';
import LineQueryForm from './components/QueryForm';
import AddLineModal from './components/AddModal';
import UpdateLineModal from './components/UpdateModal';
import { LineItem } from './data';

interface LineListProps {
  dispatch: Dispatch;
  lineList: LineItem[],
  total: number,
  loading: boolean;
  addLoading: boolean;
  updateLoading: boolean;
  deleteLoading: boolean;
  directionData: DataItem[];
  stationData: DataItem[];
  statusData: DataItem[];
}

const EMPTY_LINE: LineItem = {
  id: '',
  code: '',
  name: '',
  startStation: '',
  endStation: '',
  direction: '',
  totalLength: '',
  interval: 0,
  minTicket: '',
  maxTicket: '',
  status: ''
}

/**
 * 线路列表管理
 * @param props 属性
 * @returns 线路列表
 */
const LineList: React.FC<LineListProps> = (props) => {
  const code = 'line-list';
  const { lineList, loading, total, addLoading, updateLoading, deleteLoading, directionData, stationData, statusData } = props;
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [row, setRow] = useState<LineItem>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<LineItem[]>([]);
  const [queryParam, setQueryParam] = useState<LineItem>(EMPTY_LINE);
  const [pageSize, setPageSize] = useState<number>(10);
  const [lineFormData, setLineFormData] = useState<LineItem>(EMPTY_LINE);
  const rowKey = (record: LineItem) => {
    return record.id;
  }
  const pkField = 'id';
  const columns = [
    {
      title: '线路编码',
      dataIndex: 'code',
      render: (text: string, record: LineItem, index: number) => {
        return <a onClick={() => setRow(record)}>{text}</a>;
      },
    },
    {
      title: '线路名称',
      dataIndex: 'name',
    },
    {
      title: '起始站点',
      dataIndex: 'startStation',
      width: '250',
      render: (text: string, record: LineItem, index: number) => stationFunc(text, record)
    },
    {
      title: '终点站点',
      dataIndex: 'endStation',
      width: '250',
      render: (text: string, record: LineItem, index: number) => stationFunc(text, record)
    },
    {
      title: '总里程（公里）',
      dataIndex: 'totalLength',
    },
    {
      title: '运营间隔（分钟）',
      dataIndex: 'interval',
    },
    {
      title: '最小票价（元）',
      dataIndex: 'minTicket',
    },
    {
      title: '最大票价（元）',
      dataIndex: 'maxTicket',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text: string, record: LineItem, index: number) => lineStatusFunc(record)
    },
  ];

  useEffect(() => {
    console.info('LineList.useEffect');
    const { dispatch } = props;
    dispatch(LINE_INIT({}))
    return () => {
      const { dispatch } = props;
      dispatch(UPDATE_STATE({
        rows: [],
        total: 0
      }));
    }
  }, []);

  const lineStatusFunc = (record: LineItem) => {
    const { statusData } = props;
    const { status } = record;
    const value = getItemValue(statusData, status);
    if (status === '1') {
      return <Tag color='error'>{value}</Tag>;
    }
    return <Tag color='processing'>{value}</Tag>;
  }

  const stationFunc = (text: string, record: LineItem) => {
    const { stationData } = props;
    const value = getItemValue(stationData, text, '2');
    return value;
  }

  /**
   * 查询满足条件的数据字典
   */
  const handleQuery = (record: LineItem) => {
    console.info('LineList.handleQuery');
    console.info(record);
    const queryParam = {
      ...record
    };
    // 查询条件保存起来，方便点击页码时使用
    // setState回调方法，保证先更新state
    fetchAllLine(1, pageSize, queryParam);
  }

  const handleReset = () => {
    // 是否清空表格
  }

  /**
   * 分页查询系统参数信息
   * @param {*} pageNum 页码
   * @param {*} pageSize 每页记录条数
   */
  const fetchAllLine = (pageNum: number, pageSize: number, queryParam: LineItem) => {
    const { dispatch } = props;
    dispatch(LINE_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 删除线路，支持多笔删除
   */
  const deleteLines = async () => {
    const { dispatch } = props;
    const lineIds = [...selectedRowKeys]
    const res = await dispatch(LINE_DELETE(lineIds));
    if (res) {
      dispatch(LINE_LIST({
        ...queryParam,
        pageSize,
        pageNum: 1,
      }));
    }
  }

  /**
   * 处理按钮点击回调事件
   * @param {*} payload 数据包
   */
  const handleBtnCallBack = (callBackModel: AGridButtonCallBackModel<LineItem>) => {
    console.log('handleBtnCallBack');
    console.log(callBackModel);
    // btn 按钮
    // keys 表格勾选数组
    const { btn } = callBackModel;
    const { alias } = btn;
    // 新增
    if (alias === 'add') {
      handleAddModalVisible(true);
      return;
    }
    // 修改
    if (alias === 'edit') {
      const { rows } = callBackModel;
      setLineFormData(rows[0]);
      handleUpdateModalVisible(true);
      return;
    }
    // 删除
    if (alias === 'delete') {
      const { keys } = callBackModel;
      // 调用删除服务，删除勾选数据
      const lineId= keys[0];
      deleteLine(lineId);
      return;
    }
  }

  /**
   * 删除线路，暂时只支持单笔删除
   * @param lineId 线路id
   */
  const deleteLine = async (lineId: Key) => {
    const { dispatch } = props;
    const lineIds = [lineId]
    const res = await dispatch(LINE_DELETE(lineIds));
    if (res) {
      dispatch(LINE_LIST({
        ...queryParam,
        pageSize,
        pageNum: 1,
      }));
    }
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: LineItem[]) => {
    setSelectedRowKeys(keys);
    setSelectedRows(rows);
  };

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    setPageSize(pageSize);
    fetchAllLine(page, pageSize, queryParam);
  };

  const handleAddModal = async (record: LineItem) => {
    console.log(record);
    const { dispatch } = props;
    console.info(dispatch);
    const res = await dispatch(LINE_ADD(record));
    console.info(res);
    if (res) {
      handleAddModalVisible(false);
      fetchAllLine(1, pageSize, queryParam);
    }
  }

  const handleAddModalCancel = () => {
    handleAddModalVisible(false);
  };

  /**
   * 更新面板的确定事件
   * @param {*} record 更新表单
   */
  const handleUpdateModal = async (record: LineItem) => {
    console.log('handleUpdateModalOk');
    console.log(record);
    console.info(lineFormData);
    const { dispatch } = props;
    const res = await dispatch(LINE_UPDATE(record));
    console.info(res);
    if (res) {
      handleUpdateModalVisible(false);
      setLineFormData(EMPTY_LINE);
      fetchAllLine(1, pageSize, queryParam);
    }
  }

  const handleUpdateModalCancel = () => {
    handleUpdateModalVisible(false);
    setLineFormData(EMPTY_LINE);
  };

  return (
    <PageContainer>
      <Space direction='vertical' size='middle' style={{ display: 'flex' }}>
        <ProCard title="查询条件" headerBordered>
          <LineQueryForm
            statusData={statusData}
            colon={false}
            loading={loading}
            onSubmit={(record) => {
              setQueryParam(record);
              handleQuery(record);
            }}
            onReset={handleReset}
          />
        </ProCard>
        <ProCard>
          <AGrid
            code={code}
            btnCallBack={handleBtnCallBack}
            columns={columns}
            rowKey={rowKey}
            pkField={pkField}
            dataSource={lineList}
            loading={loading}
            total={total}
            onSelectRow={onSelectRow}
            onPageNumAndSizeChange={onPageNumAndSizeChange}
          />
        </ProCard>
      </Space>
      {selectedRows?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRows.length}</a>{' '}
              项
              &nbsp;&nbsp;
            </div>
          }
        >
          <AButton
            type='primary'
            code='batchDel'
            pageCode={code}
            name='批量删除'
            loading={deleteLoading}
            onClick={deleteLines}
          />
        </FooterToolbar>
      )}
      {
        !addModalVisible ? null :
        <AddLineModal
          directionData={directionData}
          stationData={stationData}
          statusData={statusData}
          colon={false}
          modalTitle='新增线路'
          modalWidth={1000}
          modalVisible={addModalVisible}
          loading={addLoading}
          onHandlerOK={handleAddModal}
          onHandlerCancel={handleAddModalCancel}
        />
      }
      {
        !updateModalVisible ? null :
        <UpdateLineModal
          directionData={directionData}
          stationData={stationData}
          statusData={statusData}
          colon={false}
          modalTitle=''
          modalWidth={1000}
          modalVisible={updateModalVisible}
          flag='edit'
          loading={updateLoading}
          formData={lineFormData}
          onHandlerOK={handleUpdateModal}
          onHandlerCancel={handleUpdateModalCancel}
        />
      }
      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.id && (
          <ProDescriptions<LineItem>
            column={2}
            title={row?.code}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.id,
            }}
            columns={columns as ProDescriptionsItemProps<LineItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};


export default connect((state: ConnectState) => ({
  lineList: state.lines.rows,
  total: state.lines.total,
  directionData: state.lines.directionData,
  stationData: state.lines.stationData,
  statusData: state.lines.statusData,
  loading: state.loading.effects['lines/fetchAllLine'],
  addLoading: state.loading.effects['lines/addLine'],
  updateLoading: state.loading.effects['lines/updateLine'],
  deleteLoading: state.loading.effects['lines/deleteLines'],
}))(LineList);